package com.niit.mobileDevide.age;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class AgeMapper extends Mapper<LongWritable, Text, Text, AgeBean> {

    private static final int AGE_INDEX = 8; // 年龄索引
    private static final int DEVICE_MODEL_INDEX = 1; // 设备型号索引

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        if (key.get() == 0) return; // 忽略标题行

        String[] columns = value.toString().split(",");
        if (columns.length < 10) { // 确保至少有10个字段
            System.err.println("Skipping line due to insufficient fields: " + value);
            return;
        }

        try {
            // 提取年龄作为key
            String ageStr = columns[AGE_INDEX].trim();
            int age;

            try {
                // 将年龄字符串转换为整数
                age = Integer.parseInt(ageStr);
            } catch (NumberFormatException e) {
                System.err.println("Invalid age format: " + ageStr + ". Skipping line.");
                return;
            }

            // 根据年龄数值确定年龄段
            String ageGroup;
            if (age >= 1 && age <= 25) {
                ageGroup = "0-25";
            } else if (age > 25 && age <= 50) {
                ageGroup = "25-50";
            } else if (age > 50) {
                ageGroup = "50+";
            } else {
                System.err.println("Unexpected age value: " + age + ". Skipping line.");
                return;
            }

            // 提取设备型号
            String deviceModel = columns[DEVICE_MODEL_INDEX].trim();

            // 写入键值对，键为年龄段，值为设备型号
            context.write(new Text(ageGroup), new AgeBean(deviceModel, 1));
        } catch (NumberFormatException e) {
            // 跳过格式错误的行，并打印错误信息
            System.err.println("Error parsing line: " + value + ". Error: " + e.getMessage());
        }
    }
}